<?php
declare(strict_types=1);
namespace app\admin\model;
use aphp\core\Model;
// 权限节点
class Auth extends Model
{
    protected string $table = 'auth';
    protected string $pk = 'id';

    protected array $validate = [
        ['title', 'chs_dash', '权限名格式错误', IF_MUST, AC_BOTH],
        ['controller', 'alpha_dash|unique', '控制器必须是英文|控制器已存在', IF_MUST, AC_BOTH],
        ['sort', 'number', '排序必须是数字', IF_MUST, AC_BOTH],
    ];
    protected array $auto = [
        ['controller', 'strtolower', 'function', IF_MUST, AC_BOTH],
        ['status', 1, 'string', IF_MUST, AC_INSERT],
    ];

    protected function _after_insert(array $data): void
    {
        if (isset($data['method'])) {
            $methods = config_get('sys.default_node_method', [], true);
            $auth_node = db('auth_node');
            $node = [];
            $node['auth_id'] = $data['id'];
            $node['controller'] = $data['controller'];
            $node['status'] = 1;
            foreach ($data['method'] as $method) {
                $node['title'] = $methods[$method] ?? '未设置';
                $node['method'] = $method;
                $auth_node->insert($node);
            }
        }
    }

    protected function _after_delete(array $data): void
    {
        db('auth_node')->where('auth_id', $data['id'])->delete(); // 删除节点数据
    }

    protected function _after_update(array $before, array $after): void
    {
        if ($after['controller'] != $before['controller']) {
            db('auth_node')->where('auth_id', $before['id'])->setField('controller', $after['controller']); // 更新对应名称
        }
    }
}